<template>
	<div class="menu-page table-box">
		<div v-if="SYSTEM_ID == 'sansan'" class="flex">
			<div class="w-11/12">
				<el-tabs v-model="state.type" class="bg-white pl-6 pt-2" @tab-change="loadMenuList">
					<el-tab-pane
						v-for="item in state.appletList"
						:key="item.menuSystemId || item.id"
						:label="item.name"
						:name="item.menuSystemId || item.id"
					>
					</el-tab-pane>
				</el-tabs>
			</div>
			<el-popover placement="bottom" :width="400" trigger="click">
				<template #reference>
					<el-link :underline="false" class="flex-1 bg-white pt-2"> {{ $t("common.btn.search") }}</el-link>
				</template>
				<el-input v-model="appName" :placeholder="$t('applet_dialog.placeholder.name')">
					<template #append>
						<el-button class="plus-icon iconfont iconsearch" @click="getAppletList" />
					</template>
				</el-input>
			</el-popover>
		</div>

		<ProTable
			ref="proTable"
			:title="buttonsList?.length ? '' : $t('menu.tab_title.menumanage')"
			:columns="columns"
			:requestApi="getTableList"
			:initParam="initParam"
			:dataCallback="dataCallback"
			:pagination="false"
		>
			<!-- 表格 header 按钮 -->
			<template #tableHeader="scope">
				<el-button v-for="(item, index) in buttonsList" :key="index" :type="item.btnClass" @click="clickBtn(item.path, scope)">
					<i :class="`iconfont ${item.icon}`"></i>
					{{ item.menuName }}
				</el-button>
			</template>
			<!-- 菜单类型 -->
			<template #type="scope">
				<el-tag v-if="scope.row.type == 'menu'" type="">{{ $t("menu.tag.menu") }}</el-tag>
				<el-tag v-else-if="scope.row.type == 'operate'" type="warning">{{ $t("menu.tag.operate") }}</el-tag>
				<el-tag v-else-if="scope.row.type == 'batch'" type="warning">{{ $t("menu.tag.batch") }}</el-tag>
				<el-tag v-else-if="scope.row.type == 'btn'" type="success">{{ $t("menu.tag.btn") }}</el-tag>
				<el-tag v-else type="info">{{ $t("menu.tag.other") }}</el-tag>
			</template>
			<template #enable="scope">
				<el-tag v-if="scope.row.enable == '1'">{{ $t("menu.status.enable") }}</el-tag>
				<el-tag v-else type="warning">{{ $t("menu.status.disable") }}</el-tag>
			</template>
			<!-- 图标 -->
			<template #icon="scope">
				<i :class="`iconfont ${scope.row.icon}`"></i>
			</template>
			<!-- 表格操作 -->
			<template #operation="scope">
				<el-link
					type="primary"
					v-if="buttonsList && buttonsList.find((item:any) => item.path == 'add')"
					link
					class="iconfont iconplus1"
					@click="openDrawer($t('menu.dialog_title.add'), { parentId: scope.row.id })"
					>{{ $t("menu.link.add") }}</el-link
				>
				<el-link
					type="primary"
					v-if="buttonsList && buttonsList.find((item:any) => item.path == 'mod')"
					link
					class="iconfont iconedit"
					@click="openDrawer($t('menu.dialog_title.modify'), scope.row)"
					>{{ $t("menu.link.modify") }}</el-link
				>
				<el-link
					type="primary"
					v-if="buttonsList && buttonsList.find((item:any) => item.path == 'del')"
					link
					class="iconfont icontrash-2"
					@click="deleteAccount(scope.row)"
					>{{ $t("menu.link.del") }}</el-link
				>
			</template>
		</ProTable>
		<formDialog ref="drawerRef" />
	</div>
</template>

<script setup lang="ts" name="userMenu">
import { Applet } from "@/api/interface/iot";
import { getUserAppletList } from "@/api/modules/applet/userApplet";
import { addMenu, deleteMenu, editMenu, getMenuList } from "@/api/modules/menu";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { HEADER_KEY_SYSTEM, SYSTEM_ID } from "@/config/config";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { useHandleData } from "@/hooks/useHandleData";
import { isSystem, showTips } from "@/utils/util";
import { ElMessage } from "element-plus";
import { ComponentInternalInstance, getCurrentInstance, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import formDialog from "./components/form.vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const state = reactive({
	type: "",
	appletList: [] as Applet.ResUserApplet[]
});

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	// type: 1
	sort: "order_num",
	order: true
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageIndex && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	return {
		datalist: data.records.children
		// total: data.total,
		// pageIndex: data.current,
		// pageSize: data.size
	};
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	params[HEADER_KEY_SYSTEM] = state.type;
	return getMenuList({ ...params, filter: 0 });
};
const route = useRoute();
const buttonsList = ref();
onMounted(async () => {
	getAppletList();
	// 获取页面按钮权限
	buttonsList.value = await useAuthButtons(route.meta?.id as string);
});
const appName = ref("");
const getAppletList = async () => {
	//默认是三三菜单管理
	state.type = SYSTEM_ID;

	// state.appletList = [{ id: SYSTEM_ID, key: SYSTEM_ID, name: "三三物联" }];
	if (state.type == "sansan") {
		let { result } = await getUserAppletList({ pageIndex: 1, pageSize: 99999, name: appName.value });
		state.appletList = result.records.filter((item: any) => item.type == "system" && isSystem(item.home));
		// state.appletList = state.appletList.concat(result.records || []);
		console.log(state.appletList);
	}
};
const loadMenuList = () => {
	proTable.value.clearSelection();
	proTable.value.reset();
};
const clickBtn = (val: string, scope: any) => {
	switch (val) {
		case "add":
			// openDrawer("新增", scope.selectList.length ? { parentId: scope.selectList[0].menuId } : {});
			openDrawer(proxy?.$t("menu.dialog_title.add"), {});
			break;
		case "del":
			if (scope.selectList.length == 0) return ElMessage.error(proxy?.$t("menu.elmsg.del"));
			batchDelete(scope.selectList.map((item: any) => item.id));
			break;
		case "mod":
			if (scope.selectList.length != 1) return ElMessage.error(proxy?.$t("menu.elmsg.mod"));
			openDrawer(proxy?.$t("menu.dialog_title.modify"), scope.selectList[0]);
			break;
	}
};

// 表格配置项
const columns: ColumnProps[] = [
	{ type: "selection", fixed: "left", width: "auto" },
	{
		prop: "menuName",
		label: proxy?.$t("menu.tablist_label.menuname"),
		align: "left"
	},
	{ prop: "title", label: proxy?.$t("menu.tablist_label.title"), align: "left" },
	{ prop: "icon", label: proxy?.$t("menu.tablist_label.icon"), width: 80 },
	{ prop: "type", label: proxy?.$t("menu.tablist_label.type"), width: 80 },
	{ prop: "enable", label: proxy?.$t("menu.tablist_label.enable"), width: 80 },
	{ prop: "orderNum", label: proxy?.$t("menu.tablist_label.ordernum"), width: 80 },
	{ prop: "path", label: proxy?.$t("menu.tablist_label.path"), align: "left" },
	{ prop: "component", label: proxy?.$t("menu.tablist_label.component"), align: "left" },
	{ prop: "operation", label: proxy?.$t("menu.tablist_label.operation"), fixed: "right", width: 180 }
];

// 删除行数据
const deleteAccount = async (params: Menu.MenuInfo) => {
	let { code, message } = await useHandleData(deleteMenu, { ids: params.id }, `删除【${params.menuName}】`);
	let ok = showTips(code, "删除菜单", message);
	if (ok) {
		proTable.value.clearSelection();
		proTable.value.reset();
	}
};

// 批量删除数据
const batchDelete = async (id: string[]) => {
	let { code, message } = await useHandleData(deleteMenu, { ids: id.join(",") }, "删除所选数据");
	let ok = showTips(code, "删除菜单", message);
	if (ok) {
		proTable.value.clearSelection();
		proTable.value.reset();
	}
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref();
const openDrawer = (title: string | undefined, rowData: Partial<Menu.MenuInfo> = {}) => {
	let params = {
		title,
		rowData: { ...rowData },
		isView: title === proxy?.$t("menu.dialog_title.view"),
		api: title === proxy?.$t("menu.dialog_title.add") ? addMenu : title === proxy?.$t("menu.dialog_title.modify") ? editMenu : "",
		getTableList: proTable.value.getTableList
	};
	params.rowData[HEADER_KEY_SYSTEM] = state.type;
	drawerRef.value.acceptParams(params);
};
</script>
<style lang="scss">
.menu-page {
	.el-tabs__header {
		margin: 0;
	}
}
</style>
